import { USER_ROLE, EDIT_PERMISSION_ROLES } from '@/constant/index.js'

export default {
  data() {
    return {
      userInfo: {},
      projectTypeList: [],
      lampTypeList: [],
      params: {},
      isAdmin: false,
      canEdit: false,
      powerPriceMap: {}
    }
  },
  onLoad(option) {
    console.log(option)
    const self = this
    Object.assign(self.params, option)
  },
  mounted() {
    const self = this
    uni.getStorage({
      key: 'userInfo',
      success(result) {
        try {
          self.userInfo = JSON.parse(result.data)
          self.isAdmin = self.userInfo.role === USER_ROLE.ADMIN
          self.canEdit = EDIT_PERMISSION_ROLES.includes(self.userInfo.role)
        } catch (e) {
          console.warn('获取userInfo失败', e)
        }
      }
    })
    uni.getStorage({
      key: 'projectType',
      success(result) {
        try {
          const projectType = JSON.parse(result.data)
          if (Array.isArray(projectType)) {
            self.projectTypeList = projectType
          }
        } catch (e) {
          console.warn('获取projectType失败', e)
        }
      }
    })
    uni.getStorage({
      key: 'lampType',
      success(result) {
        try {
          const lampType = JSON.parse(result.data)
          if (Array.isArray(lampType)) {
            self.lampTypeList = lampType
          }
        } catch (e) {
          console.warn('获取lampType失败', e)
        }
      }
    })
  },
  methods: {
    getPowerPrice(projectType, province) {
      const self = this
      return new Promise(resolve => {
        const key = `${projectType}-${province}`
        if (projectType === undefined || !province) {
          resolve(0)
        } else if (self.powerPriceMap[key]) {
          resolve(self.powerPriceMap[key])
        } else {
          uni.request({
            url: '/sys/power_rate',
            method: 'POST',
            data: {
              xm_type: projectType,
              province,
            },
            success(result) {
              if (result.data.success && result.data.data?.[0]?.price) {
                self.powerPriceMap[key] = parseFloat(result.data.data?.[0]?.price) || 0
                resolve(self.powerPriceMap[key])
              } else {
                resolve(0)
              }
            },
            fail() {
              resolve(0)
            }
          })
        }
      })
    }
  }
}
